<?php
namespace Web\Widget;
use Think\Controller;

class PagerWidget extends Controller {

    public function widget($data){
        $total = v($data,'total',0);

        $size = v($data,'size',20);

        $listnum = v($data,'listnum',5);

        if(!$total || !$size) return '';

        $pagenum = ceil($total/$size);

        $p = I('get.p',1,'intval');

        if($p < 1) $p = 1;

        if($p > $pagenum) $p = $pagenum;

        $_GET['p'] = 'PAGE';

        $url = U(ACTION_NAME, I('get.'));
        // 首页
        $first = array(
            'url'       =>  str_replace('PAGE',1,$url),
            'current'   =>  ($p == 1) ? 1 : 0
        );
        // 尾页
        $last = array(
            'url'       =>  str_replace('PAGE',$pagenum,$url),
            'current'   =>  ($p == $pagenum) ? 1 : 0
        );
        // 上一页
        $prevnum = ($p <= 1) ? 1 : $p - 1;
        $prev = array(
            'url'       =>  str_replace('PAGE',$prevnum,$url),
            'current'   =>  ($p == $prevnum) ? 1 : 0
        );
        // 下一页
        $nextnum = ($p >= $pagenum) ? $pagenum : $p + 1;
        $next = array(
            'url'       =>  str_replace('PAGE',$nextnum,$url),
            'current'   =>  ($p == $nextnum) ? 1 : 0
        );

        // 单页列表
        if($pagenum <= $listnum) {
            $start_page_num = 1;
            $end_page_num = $pagenum;
        }else {
            $sepnum = intval($listnum/2) ;
            $start_page_num = ($p - $sepnum < 1) ? 1 : $p - $sepnum;
            if($start_page_num + $listnum <= $pagenum) {
                $end_page_num = $start_page_num + $listnum - 1;
            }else {
                $end_page_num = $pagenum;
                $start_page_num = $end_page_num - $listnum + 1;
            }
        }

        for($i=$start_page_num;$i<=$end_page_num;$i++) {
            $list[$i] = array(
                'url'       =>  str_replace('PAGE',$i,$url),
                'current'   =>  ($p == $i) ? 1 : 0

            );
        }

        $pageData = array(
            'total' =>  $total,
            'size'  =>  $size,
            'first' =>  $first,
            'last'  =>  $last,
            'prev'  =>  $prev,
            'next'  =>  $next,
            'list'  =>  $list,
            'pagenum'   =>  $pagenum,
        );
        $this->assign('pageData',$pageData);

        return $this->fetch('Public:page');
    } 
}
?>
